# -*- mode: python -*-
#
#    Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
#
#    This file is part of DCP-o-matic.
#
#    DCP-o-matic is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    DCP-o-matic is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
#

from __future__ import print_function
import glob
import shutil
import os
import copy
import json

deb_build_depends = dict()

deb_build_depends_base = ['debhelper', 'python', 'g++', 'pkg-config', 'libsndfile1-dev', 'libgtk2.0-dev', 'libx264-dev']

deb_build_depends['16.04'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['16.04'].extend(['libssh-dev'])
deb_build_depends['18.04'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['18.04'].extend(['libssh-dev'])
deb_build_depends['19.04'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['19.04'].extend(['libssh-dev'])
deb_build_depends['19.10'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['19.10'].extend(['libssh-dev'])
deb_build_depends['20.04'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['20.04'].extend(['libssh-dev'])
deb_build_depends['7'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['7'].extend(['libssh-dev'])
deb_build_depends['8'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['8'].extend(['libssh-gcrypt-dev'])
deb_build_depends['9'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['9'].extend(['libssh-gcrypt-dev'])
deb_build_depends['10'] = copy.deepcopy(deb_build_depends_base)
deb_build_depends['10'].extend(['libssh-gcrypt-dev'])
deb_build_depends['unstable'] = copy.deepcopy(deb_build_depends_base)

deb_depends = dict()
deb_depends_gui = dict()

deb_depends_base = ['libc6', 'libsndfile1', 'libsamplerate0', 'libxmlsec1', 'libxmlsec1-openssl', 'libgtk2.0-0']

deb_depends['16.04'] = copy.deepcopy(deb_depends_base)
deb_depends['16.04'].extend(['libboost-filesystem1.58.0',
                             'libboost-thread1.58.0',
                             'libboost-regex1.58.0',
                             'libxml++2.6-2v5',
                             'libboost-date-time1.58.0',
                             'libzip4',
                             'libcairomm-1.0-1v5',
                             'libpangomm-1.4-1v5',
                             'libwxgtk3.0-0v5',
                             'libicu55',
                             'libnettle6',
                             'libssh-4',
                             'libx264-148',
                             'libcurl3'])

deb_depends['18.04'] = copy.deepcopy(deb_depends_base)
deb_depends['18.04'].extend(['libboost-filesystem1.65.1',
                             'libboost-thread1.65.1',
                             'libboost-regex1.65.1',
                             'libboost-date-time1.65.1',
                             'libcairomm-1.0-1v5',
                             'libpangomm-1.4-1v5',
                             'libxml++2.6-2v5',
                             'libzip4',
                             'libwxgtk3.0-0v5',
                             'libicu60',
                             'libnettle6',
                             'libssh-4',
                             'libx264-152',
                             'libcurl4',
                             'libpulse0'])

deb_depends['19.04'] = copy.deepcopy(deb_depends_base)
deb_depends['19.04'].extend(['libboost-filesystem1.67.0',
                             'libboost-thread1.67.0',
                             'libboost-regex1.67.0',
                             'libboost-date-time1.67.0',
                             'libcairomm-1.0-1v5',
                             'libpangomm-1.4-1v5',
                             'libxml++2.6-2v5',
                             'libzip5',
                             'libwxgtk3.0-0v5',
                             'libicu63',
                             'libnettle6',
                             'libssh-4',
                             'libx264-155',
                             'libcurl4',
                             'libpulse0'])

deb_depends['19.10'] = copy.deepcopy(deb_depends_base)
deb_depends['19.10'].extend(['libboost-filesystem1.67.0',
                             'libboost-thread1.67.0',
                             'libboost-regex1.67.0',
                             'libboost-date-time1.67.0',
                             'libcairomm-1.0-1v5',
                             'libpangomm-1.4-1v5',
                             'libxml++2.6-2v5',
                             'libzip5',
                             'libwxgtk3.0-0v5',
                             'libicu63',
                             'libnettle6',
                             'libssh-4',
                             'libx264-155',
                             'libcurl4',
                             'libpulse0'])

deb_depends['20.04'] = copy.deepcopy(deb_depends_base)
deb_depends['20.04'].extend(['libboost-filesystem1.71.0',
                             'libboost-thread1.71.0',
                             'libboost-regex1.71.0',
                             'libboost-date-time1.71.0',
                             'libcairomm-1.0-1v5',
                             'libpangomm-1.4-1v5',
                             'libxml++2.6-2v5',
                             'libzip5',
                             'libwxgtk3.0-gtk3-0v5',
                             'libicu66',
                             'libnettle7',
                             'libssh-4',
                             'libx264-155',
                             'libcurl4',
                             'libpulse0',
                             'libxerces-c3.2',
                             'libnanomsg5'])

deb_depends['8'] = copy.deepcopy(deb_depends_base)
deb_depends['8'].extend(['libboost-filesystem1.55.0',
                         'libboost-thread1.55.0',
                         'libboost-date-time1.55.0',
                         'libboost-regex1.55.0',
                         'libxml++2.6-2',
                         'libzip2',
                         'libcairomm-1.0-1',
                         'libpangomm-1.4-1',
                         'libwxgtk3.0-0',
                         'libxcb-xfixes0',
                         'libxcb-shape0',
                         'libicu52',
                         'libnettle4',
                         'libssh-4',
                         'libx264-142',
                         'libcurl3'])

deb_depends['9'] = copy.deepcopy(deb_depends_base)
deb_depends['9'].extend(['libboost-filesystem1.62.0',
                         'libboost-thread1.62.0',
                         'libboost-regex1.62.0',
                         'libboost-date-time1.62.0',
                         'libxml++2.6-2v5',
                         'libgtk2.0-0',
                         'libzip4',
                         'libcairomm-1.0-1v5',
                         'libpangomm-1.4-1v5',
                         'libicu57',
                         'libssh-4',
                         'libssh-gcrypt-4',
                         'libnettle6',
                         'libx264-148',
                         'libcurl3'])

deb_depends_gui['9'] = [ 'libwxgtk3.0-0v5',
                         'libxcb-xfixes0',
                         'libxcb-shape0',
                         'libasound2',
                         'libpulse0' ]

deb_depends['10'] = copy.deepcopy(deb_depends_base)
deb_depends['10'].extend(['libboost-filesystem1.67.0',
                          'libboost-thread1.67.0',
                          'libboost-regex1.67.0',
                          'libboost-date-time1.67.0',
                          'libxml++2.6-2v5',
                          'libgtk2.0-0',
                          'libzip4',
                          'libcairomm-1.0-1v5',
                          'libpangomm-1.4-1v5',
                          'libicu63',
                          'libssh-4',
                          'libssh-gcrypt-4',
                          'libnettle6',
                          'libx264-155',
                          'libcurl4'])

deb_depends_gui['10'] = [ 'libwxgtk3.0-0v5',
                          'libxcb-xfixes0',
                          'libxcb-shape0',
                          'libasound2',
                          'libpulse0' ]

deb_depends['unstable'] = copy.deepcopy(deb_depends_base)
deb_depends['unstable'].extend(['libboost-filesystem1.67.0',
                                'libboost-thread1.67.0',
                                'libboost-regex1.67.0',
                                'libboost-date-time1.67.0',
                                'libxml++2.6-2v5',
                                'libgtk2.0-0',
                                'libzip4',
                                'libicu63',
                                'libnettle6',
                                'libx264-155',
                                'libcurl4'])

def packages(name, packages, f):
    s = '%s: ' % name
    for p in packages:
        s += str(p) + ', '
    print(s[:-2], file=f)

def make_control(debian_version, bits, filename, debug, gui):
    f = open(filename, 'w')
    print('Source: dcpomatic', file=f)
    print('Section: video', file=f)
    print('Priority: extra', file=f)
    print('Maintainer: Carl Hetherington <carl@dcpomatic.com>', file=f)
    packages('Build-Depends', deb_build_depends[debian_version], f)
    print('Standards-Version: 3.9.3', file=f)
    print('Homepage: https://dcpomatic.com/', file=f)
    print('', file=f)
    print('Package: dcpomatic', file=f)
    if bits == 32:
        print('Architecture: i386', file=f)
    else:
        print('Architecture: amd64', file=f)

    pkg = deb_depends[debian_version]
    if gui and debian_version in deb_depends_gui:
        pkg.extend(deb_depends_gui[debian_version])

    packages('Depends', pkg, f)

    print('Description: Generator of Digital Cinema Packages (DCPs)', file=f)
    print('  DCP-o-matic generates Digital Cinema Packages (DCPs) from videos, images,', file=f)
    print('  sound and subtitle files.  You can use it to make content for playback on DCI-compliant', file=f)
    print('  cinema projectors.', file=f)

    if debug:
        print('', file=f)
        print('Package: dcpomatic-dbg', file=f)
        if bits == 32:
            print('Architecture: i386', file=f)
        else:
            print('Architecture: amd64', file=f)
        print('Section: debug', file=f)
        print('Priority: extra', file=f)
        packages('Depends', pkg, f)
        print('Description: debugging symbols for dcpomatic', file=f)
        print('  This package contains the debugging symbols for dcpomatic.', file=f)
        print('', file=f)

def make_spec(filename, version, target, options, requires=None):
    """Make a .spec file for a RPM build"""
    f = open(filename, 'w')
    print('Summary:A program that generates Digital Cinema Packages (DCPs) from video and audio files', file=f)
    print('Name:dcpomatic2', file=f)
    print('Version:%s' % version, file=f)
    print('Release:1%{?dist}', file=f)
    print('License:GPL', file=f)
    print('Group:Applications/Multimedia', file=f)
    print('URL:https://dcpomatic.com/', file=f)
    if requires is not None:
        print('Requires:%s' % requires, file=f)
    print('', file=f)
    print('%description', file=f)
    print('DCP-o-matic generates Digital Cinema Packages (DCPs) from video and audio ', file=f)
    print('files for presentation on DCI-compliant digital projectors.', file=f)
    print('', file=f)
    print('%files', file=f)
    print('%{_bindir}/dcpomatic2', file=f)
    print('%{_bindir}/dcpomatic2_batch', file=f)
    print('%{_bindir}/dcpomatic2_cli', file=f)
    print('%{_bindir}/dcpomatic2_create', file=f)
    print('%{_bindir}/dcpomatic2_kdm', file=f)
    print('%{_bindir}/dcpomatic2_server', file=f)
    print('%{_bindir}/dcpomatic2_server_cli', file=f)
    print('%{_bindir}/dcpomatic2_kdm_cli', file=f)
    print('%{_bindir}/dcpomatic2_player', file=f)
    print('%{_bindir}/dcpomatic2_playlist', file=f)
    print('%{_datadir}/applications/dcpomatic2.desktop', file=f)
    print('%{_datadir}/applications/dcpomatic2_batch.desktop', file=f)
    print('%{_datadir}/applications/dcpomatic2_server.desktop', file=f)
    print('%{_datadir}/applications/dcpomatic2_kdm.desktop', file=f)
    print('%{_datadir}/applications/dcpomatic2_player.desktop', file=f)
    print('%{_datadir}/applications/dcpomatic2_playlist.desktop', file=f)
    print('%{_datadir}/dcpomatic2/dcpomatic2_server_small.png', file=f)
    print('%{_datadir}/dcpomatic2/select.png', file=f)
    print('%{_datadir}/dcpomatic2/sequence.png', file=f)
    print('%{_datadir}/dcpomatic2/snap.png', file=f)
    print('%{_datadir}/dcpomatic2/zoom.png', file=f)
    print('%{_datadir}/dcpomatic2/zoom_all.png', file=f)
    print('%{_datadir}/dcpomatic2/tick.png', file=f)
    print('%{_datadir}/dcpomatic2/no_tick.png', file=f)
    print('%{_datadir}/dcpomatic2/me.jpg', file=f)
    print('%{_datadir}/dcpomatic2/LiberationSans-Regular.ttf', file=f)
    print('%{_datadir}/dcpomatic2/LiberationSans-Italic.ttf', file=f)
    print('%{_datadir}/dcpomatic2/LiberationSans-Bold.ttf', file=f)
    print('%{_datadir}/dcpomatic2/splash.png', file=f)
    for r in ['128x128', '16x16', '22x22', '256x256', '32x32', '48x48', '512x512', '64x64']:
        print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2.png' % r, file=f)
        print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_batch.png' % r, file=f)
        print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_kdm.png' % r, file=f)
        print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_server.png' % r, file=f)
        print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_player.png' % r, file=f)
        print('%%{_datadir}/icons/hicolor/%s/apps/dcpomatic2_playlist.png' % r, file=f)
    for l in ['de_DE', 'es_ES', 'fr_FR', 'it_IT', 'sv_SE', 'nl_NL', 'ru_RU', 'pl_PL', 'da_DK',
              'pt_PT', 'pt_BR', 'sk_SK', 'cs_CZ', 'uk_UA', 'zh_CN', 'tr_TR', 'ko_KR']:
        print('%%{_datadir}/locale/%s/LC_MESSAGES/dcpomatic2.mo' % l, file=f)
        print('%%{_datadir}/locale/%s/LC_MESSAGES/libdcpomatic2-wx.mo' % l, file=f)
        print('%%{_datadir}/locale/%s/LC_MESSAGES/libdcpomatic2.mo' % l, file=f)
    print('', file=f)
    print('%prep', file=f)
    print('rm -rf $RPM_BUILD_DIR/dcpomatic-%s' % version, file=f)
    print('tar xjf $RPM_SOURCE_DIR/dcpomatic-%s.tar.bz2' % version, file=f)
    print('%build', file=f)
    print('cd dcpomatic-%s' % version, file=f)
    print('export PKG_CONFIG_PATH=%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib/pkgconfig:/usr/local/lib64/pkgconfig' % (target.directory, target.directory), file=f)

    print('CXXFLAGS="-I%s/include" LDFLAGS="-L%s/lib" ./waf configure --prefix=%%{buildroot}/usr --install-prefix=/usr %s' %
          (target.directory, target.directory, configure_options(target, options)), file=f)
    print('./waf', file=f)
    print('%install', file=f)
    print('cd dcpomatic-%s' % version, file=f)
    print('./waf install', file=f)
    print('', file=f)
    print('%post', file=f)
    print('/bin/touch --no-create %{_datadir}/icons/hicolor &>/dev/null || :', file=f)
    print('', file=f)
    print('%postun', file=f)
    print('if [ $1 -eq 0 ] ; then', file=f)
    print('    /bin/touch --no-create %{_datadir}/icons/hicolor &>/dev/null', file=f)
    print('    /usr/bin/gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || :', file=f)
    print('fi', file=f)
    print('', file=f)
    print('%posttrans', file=f)
    print('/usr/bin/gtk-update-icon-cache %{_datadir}/icons/hicolor &>/dev/null || :', file=f)

def dependencies(target):

    if target.platform == 'linux':
        ffmpeg_options = { 'shared': False }
    else:
        ffmpeg_options = {}

    if target.platform == 'windows' and target.version == 'xp':
        deps = [('ffmpeg-cdist', '5783efa', ffmpeg_options)]
    elif target.platform != 'linux' or target.distro != 'arch':
        deps = [('ffmpeg-cdist', 'a820b44', ffmpeg_options)]
    else:
        # Use distro-provided FFmpeg on Arch
        deps = []

    deps.append(('libdcp', 'v1.6.15'))
    deps.append(('libsub', 'v1.4.19'))
    deps.append(('rtaudio-cdist', 'bf0fc23'))

    return deps

def option_defaults():
    return { "gui": True, "variant": None }

def configure_options(target, options):
    opt = ''

    if not (target.platform == 'linux' and target.distro == 'ubuntu' and target.version == '18.04'):
        # Currently we only build tests on Ubuntu 18.04
        opt += ' --disable-tests'

    if target.debug:
        opt += ' --enable-debug'
    if target.platform == 'windows':
        opt += ' --target-windows'
    elif target.platform == 'linux':
        opt += ' --static-dcpomatic --static-wxwidgets --static-ffmpeg --static-dcp --static-sub --static-cxml'
        if target.distro == 'centos':
            if target.version == '6.5':
                opt += ' --static-boost --static-xmlpp'
            elif target.version == '7':
                opt += ' --workaround-gssapi'
                # Centos 7 ships with glibmm 2.50.0 which requires C++11
                # but its compiler (gcc 4.8.5) defaults to C++97.  Go figure.
                # I worry that this will cause ABI problems but I don't have
                # a better solution.
                opt += ' --force-cpp11'

    if not options['gui']:
        opt += ' --disable-gui'

    if options['variant'] is not None:
        opt += ' --variant=%s' % options['variant']

    # Build Windows debug versions with static linking as I think gdb works better then
    if target.debug and target.platform == 'windows':
        opt += ' --static-dcpomatic'

    return opt

def build(target, options):
    if target.platform == 'flatpak':
        target.checkout_dependencies()
        prefix = 'https://dcpomatic.com/deps'
        modules = []
        modules.append({'name': 'libzip',
                        'buildsystem': 'cmake',
                        'sources': [{'type': 'archive',
                                     'url': '%s/libzip-1.4.0.tar.xz' % prefix,
		                     'sha256': 'e508aba025f5f94b267d5120fc33761bcd98440ebe49dbfe2ed3df3afeacc7b1'}]})
        modules.append({'name': 'libsigc++',
                        'sources': [{'type': 'archive',
                                     'url': '%s/libsigc++-2.10.0.tar.xz' % prefix,
                                     'sha256': 'f843d6346260bfcb4426259e314512b99e296e8ca241d771d21ac64f28298d81'}]})
        modules.append({'name': 'glibmm',
                        'sources': [{'type': 'archive',
                                     'url': '%s/glibmm-2.48.1.tar.xz' % prefix,
                                     'sha256': 'dc225f7d2f466479766332483ea78f82dc349d59399d30c00de50e5073157cdf'}]})
        modules.append({'name': 'cairomm',
                        'sources': [{'type': 'archive',
                                     'url': '%s/cairomm-1.12.2.tar.gz' % prefix,
                                     'sha256': '45c47fd4d0aa77464a75cdca011143fea3ef795c4753f6e860057da5fb8bd599'}]})
        modules.append({'name': 'pangomm',
	                'sources': [{'type': 'archive',
		                     'url': '%s/pangomm-2.40.1.tar.xz' % prefix,
		                     'sha256': '9762ee2a2d5781be6797448d4dd2383ce14907159b30bc12bf6b08e7227be3af'}]})
        modules.append({'name': 'libxml++',
	                'sources': [{'type': 'archive',
		                     'url': '%s/libxml++-2.40.1.tar.xz' % prefix,
		                     'sha256': '4ad4abdd3258874f61c2e2a41d08e9930677976d303653cd1670d3e9f35463e9'}]})
        modules.append({'name': 'xmlsec1',
	                'sources': [{'type': 'archive',
		                     'url': '%s/xmlsec1-1.2.25.tar.gz' % prefix,
		                     'sha256': '967ca83edf25ccb5b48a3c4a09ad3405a63365576503bf34290a42de1b92fcd2'}]}) 
        modules.append({'name': 'openjpeg2',
	                'buildsystem': 'cmake',
	                'sources': [{'type': 'dir', 'path': os.path.abspath('../openjpeg2-cdist')}]})
        modules.append({'name': 'boost',
	                'buildsystem': 'simple',
	                'build-commands': [
		            './bootstrap.sh --prefix=/app',
		            './b2 install'
	                ],
	                'sources': [{'type': 'archive',
		                     'url': '%s/boost_1_66_0.tar.bz2' % prefix,
		                     'sha256': '5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9'}]})
        modules.append({'name': 'asdcplib',
	                'buildsystem': 'simple',
	                'build-commands': [
		            './waf configure --prefix=/app  --libdir=/app/lib build install'
	                ],
	                'sources': [{'type': 'dir', 'path': os.path.abspath('../asdcplib-cth')}]})
        modules.append({'name': 'locked_sstream',
	                'buildsystem': 'simple',
	                'build-commands': [
		            './waf configure --prefix=/app build install'
	                ],
	                'sources': [{'type': 'dir', 'path': os.path.abspath('../locked_sstream')}]})
        modules.append({'name': 'libcxml',
	                'buildsystem': 'simple',
	                'build-commands': [
		            './waf configure --prefix=/app  --libdir=/app/lib build install'
	                ],
	                'sources': [{'type': 'dir', 'path': os.path.abspath('../libcxml')}]})
        modules.append({'name': 'libdcp',
	                'buildsystem': 'simple',
	                'build-commands': [
		            './waf configure --prefix=/app --libdir=/app/lib build install'
	                ],
	                'sources': [{'type': 'dir', 'path': os.path.abspath('../libdcp')}]})
        modules.append({'name': 'libsub',
	                'buildsystem': 'simple',
	                'build-commands': [
		            './waf configure --prefix=/app --libdir=/app/lib build install'
	                ],
	                'sources': [{'type': 'dir', 'path': os.path.abspath('../libsub')}]})
        modules.append({'name': 'rtaudio',
	                'build-options': {
		            'config-opts': [
		                '--prefix=/app',
		                '--with-pulse',
		                '--with-alsa'
		            ]
	                },
	                'sources': [{'type': 'dir', 'path': os.path.abspath('../rtaudio-cdist')}]})
        modules.append({'name': 'wxwidgets',
	                'sources': [{'type': 'archive',
		                     'url': '%s/wxWidgets-3.0.3.tar.bz2' % prefix,
		                     'sha256': '08c8033f48ec1b23520f036cde37b5ae925a6a65f137ded665633ca159b9307b'}]})
        modules.append({'name': 'libssh',
	                'buildsystem': 'cmake',
	                'builddir': True,
	                'sources': [{'type': 'archive',
		                     'url': '%s/libssh-0.7.5.tar.xz' % prefix,
		                     'sha256': '54e86dd5dc20e5367e58f3caab337ce37675f863f80df85b6b1614966a337095'}]})
        modules.append({'name': 'dcpomatic',
	                'buildsystem': 'simple',
	                'build-commands': [
		            './waf configure --prefix=/app build install'
	                ],
                        'build-options': {
                            'build-args': ['--share=network']
                        },
	                'sources': [{'type': 'dir', 'path': os.path.abspath('.')}]})
        desc = {'app-id': 'com.dcpomatic.DCP-o-matic',
                'runtime': 'org.gnome.Sdk',
                'runtime-version': '3.26',
                'sdk': 'org.gnome.Sdk',
                'command': 'dcpomatic2',
                'finish-args': ['--socket=x11', '--share=ipc', '--share=network', '--socket=pulseaudio', '--filesystem=host'],
                'modules': modules}
        os.makedirs('build/platform')
        with open('build/com.dcpomatic.DCP-o-matic.json', 'w') as outfile:
            json.dump(desc, outfile)
        target.command('%s --repo=build/platform/repo build/platform/flatpak build/com.dcpomatic.DCP-o-matic.json' % target.flatpak_builder())
    else:
        target.command('./waf configure --prefix=%s %s' % (target.directory, configure_options(target, options)))
        target.command('./waf')

        if target.platform == 'linux' or target.platform == 'osx':
            target.command('./waf install')

def package_windows(target):
    identifier = ''
    if target.version is not None:
        identifier = '%s.' % target.version
    identifier += '%d' % target.bits
    shutil.copyfile('build/platform/windows/installer.%s.nsi' % identifier, 'build/platform/windows/installer2.%s.nsi' % identifier)
    target.command('sed -i "s~%%resources%%~%s/platform/windows~g" build/platform/windows/installer2.%s.nsi' % (os.getcwd(), identifier))
    target.command('sed -i "s~%%graphics%%~%s/graphics~g" build/platform/windows/installer2.%s.nsi' % (os.getcwd(), identifier))
    target.command('sed -i "s~%%static_deps%%~%s~g" build/platform/windows/installer2.%s.nsi' % (target.windows_prefix, identifier))
    target.command('sed -i "s~%%cdist_deps%%~%s~g" build/platform/windows/installer2.%s.nsi' % (target.directory, identifier))
    target.command('sed -i "s~%%mingw%%~%s~g" build/platform/windows/installer2.%s.nsi' % (target.environment_prefix, identifier))
    target.command('sed -i "s~%%binaries%%~%s/build~g" build/platform/windows/installer2.%s.nsi' % (os.getcwd(), identifier))
    target.command('sed -i "s~%%bits%%~32~g" build/platform/windows/installer2.%s.nsi' % identifier)
    target.command('makensis build/platform/windows/installer2.%s.nsi' % identifier)
    return os.path.abspath(glob.glob('build/platform/windows/*%s*.exe' % target.bits)[0])

def package_debian(target, cpu, version, options):
    make_control(target.version, target.bits, 'debian/control', target.debug, options['gui'])
    target.command('./waf dist')
    f = open('debian/files', 'w')
    print('dcpomatic_%s-1_%s.deb video extra' % (version, cpu), file=f)
    shutil.rmtree('build/deb', ignore_errors=True)

    os.makedirs('build/deb')
    os.chdir('build/deb')
    shutil.move('../../dcpomatic-%s.tar.bz2' % version, 'dcpomatic_%s.orig.tar.bz2' % version)
    target.command('tar xjf dcpomatic_%s.orig.tar.bz2' % version)
    os.chdir('dcpomatic-%s' % version)
    target.command('dch -b -v %s-1 "New upstream release."' % version)
    target.set('CDIST_LINKFLAGS', target.get('LINKFLAGS'))
    target.set('CDIST_CXXFLAGS', target.get('CXXFLAGS'))
    target.set('CDIST_PKG_CONFIG_PATH', target.get('PKG_CONFIG_PATH'))

    target.set('CDIST_CONFIGURE', '"' + configure_options(target, options) + '"')
    if target.debug:
        target.set('CDIST_DEBUG_PACKAGE', '--dbg-package=dcpomatic-dbg')
    if target.version in ['7', '14.04']:
        target.set('CDIST_LOCALE_PREFIX', '/usr/local/share/locale')
    else:
        target.set('CDIST_LOCALE_PREFIX', '/usr/share/locale')

    target.command('dpkg-buildpackage -uc -us')

    debs = []
    for p in glob.glob('../*.deb'):
        debs.append(os.path.abspath(p))

    return debs

def package_rpm(target, cpu, version, options):
    topdir = os.path.realpath('build/rpmbuild')
    os.makedirs('%s/BUILD' % topdir)
    os.makedirs('%s/RPMS' % topdir)
    os.makedirs('%s/SOURCES' % topdir)
    os.makedirs('%s/SPECS' % topdir)
    os.makedirs('%s/SRPMS' % topdir)

    target.command('./waf dist')
    shutil.copyfile(
        "%s/src/dcpomatic/dcpomatic-%s.tar.bz2" % (target.directory, version),
        "%s/SOURCES/dcpomatic-%s.tar.bz2" % (topdir, version)
        )

    requires = None
    if target.distro == 'mageia':
        requires = "lib64xmlsec1-devel"

    make_spec('build/platform/linux/dcpomatic2.spec', version, target, options, requires)
    cmd = 'rpmbuild --define "_topdir %s" -bb build/platform/linux/dcpomatic2.spec' % topdir
    target.command(cmd)
    rpms = []

    if cpu == "amd64":
        cpu = "x86_64"
    else:
        cpu = "i686"

    for p in glob.glob('%s/RPMS/%s/*.rpm' % (topdir, cpu)):
        rpms.append(os.path.abspath(p))

    return rpms

def make_appimage(target, nice_name, internal_name, version):
    nice_filename = nice_name.replace(' ', '_')
    os.makedirs('build/%s.AppDir/usr/bin' % nice_filename)
    target.command('cp %s/bin/%s build/%s.AppDir/usr/bin' % (target.directory, internal_name, nice_filename))
    with open('build/%s.AppDir/AppRun' % nice_filename, 'w') as f:
        print('#!/bin/bash', file=f)
        print('export APPDIR="$(dirname "$(readlink -f "$0")")"', file=f)
        print('export PATH=$APPDIR/usr/bin:$PATH', file=f)
        print('export XDG_DATA_DIRS="$APPDIR/usr/share/:/usr/share/:$XDG_DATA_DIRS"', file=f)
        print('"$APPDIR"/usr/bin/%s $@' % internal_name, file=f)
    target.command('chmod a+rx build/%s.AppDir/AppRun' % nice_filename)
    with open('build/%s.AppDir/%s.desktop' % (nice_filename, internal_name), 'w') as f:
        print('[Desktop Entry]', file=f)
        print('Type=Application', file=f)
        print('Categories=AudioVideo;', file=f)
        print('Name=%s' % nice_name, file=f)
        print('Icon=%s' % internal_name, file=f)
    target.command('cp graphics/linux/256/%s.png build/%s.AppDir' % (internal_name, nice_filename))
    target.command('linuxdeploy-x86_64.AppImage --appdir build/%s.AppDir' % nice_filename)
    target.command('appimagetool-x86_64.AppImage build/%s.AppDir' % nice_filename)
    target.command('mv %s-x86_64.AppImage build/%s-%s-x86_64.AppImage' % (nice_filename, nice_filename, version))
    return os.path.abspath('build/%s-%s-x86_64.AppImage' % (nice_filename, version))

def package(target, version, options):
    """version: DCP-o-matic version string"""
    if target.platform == 'windows':
        return package_windows(target)
    elif target.platform == 'linux':
        if target.detail == 'appimage':
            out = []
            out.append(make_appimage(target, 'DCP-o-matic', 'dcpomatic2', version))
            out.append(make_appimage(target, 'DCP-o-matic Player', 'dcpomatic2_player', version))
            out.append(make_appimage(target, 'DCP-o-matic Playlist Editor', 'dcpomatic2_playlist', version))
            out.append(make_appimage(target, 'DCP-o-matic KDM Creator', 'dcpomatic2_kdm', version))
            out.append(make_appimage(target, 'DCP-o-matic Batch Converter', 'dcpomatic2_batch', version))
            out.append(make_appimage(target, 'DCP-o-matic Encode Server', 'dcpomatic2_server', version))
            return out
        else:
            if target.bits == 32:
                cpu = 'i386'
            else:
                cpu = 'amd64'

            if target.distro == 'debian' or target.distro == 'ubuntu':
                return package_debian(target, cpu, version, options)
            elif target.distro == 'centos' or target.distro == 'fedora' or target.distro == 'mageia':
                return package_rpm(target, cpu, version, options)
    elif target.platform == 'osx' and target.bits is None:
        target.command('bash platform/osx/make_dmg.sh %s %s universal %s %s' % (target.environment_prefix, target.directory, target.apple_id, target.apple_password))
        return [os.path.abspath(x) for x in glob.glob('build/platform/osx/DCP-o-matic*.dmg')]
    elif target.platform == 'osx' and target.bits == 64:
        target.command('bash platform/osx/make_dmg.sh %s %s thin %s %s' % (target.environment_prefix, target.directory, target.apple_id, target.apple_password))
        return [os.path.abspath(x) for x in glob.glob('build/platform/osx/DCP-o-matic*.dmg')]
    elif target.platform == 'docker':
        shutil.copyfile(target.deb, 'build/platform/docker')
        f = open('build/platform/docker/Dockerfile', 'w')
        print('FROM debian:jessie', file=f)
        print('MAINTAINER carl@dcpomatic.com', file=f)
        print('ADD build/platform/docker/dcpomatic_%s-1_amd64.deb /tmp' % (version, version), file=f)
        print('RUN apt-get -o Acquire:http::Timeout="5" update; exit 0', file=f)
        print('RUN dpkg -i /tmp/dcpomatic_*.deb; exit 0', file=f)
        print('RUN apt-get -y -f install', file=f)
        print('RUN apt-get clean', file=f)
        print('EXPOSE 6192', file=f)
        print('CMD ["/usr/bin/dcpomatic2_server_cli", "--verbose"]', file=f)
        f.close()
        target.command('docker build build/platform/docker -t dcpomatic-server:%s' % version)
        target.command('docker save dcpomatic-server:%s -o dcpomatic-server-%s-docker.tar' % (version, version))
    elif target.platform == 'flatpak':
        target.command('%s build-bundle build/platform/repo build/dcpomatic_%s.flatpak com.dcpomatic.DCP-o-matic' % (target.flatpak(), version))
        return os.path.abspath('build/dcpomatic_%s.flatpak' % version)

def make_pot(target):
    target.command('./waf pot')
    return [os.path.abspath('build/src/lib/libdcpomatic.pot'),
            os.path.abspath('build/src/wx/libdcpomatic-wx.pot'),
            os.path.abspath('build/src/tools/dcpomatic.pot')]

def make_manual(target):
    os.chdir('doc/manual')
    target.command('make')
    target.command('pdflatex colour.tex')
    return [os.path.abspath('pdf'), os.path.abspath('html'), os.path.abspath('colour.pdf')]

def test(target, test):
    if target.platform != 'windows':
        target.set('LC_ALL', 'C')
        cmd = 'run/tests '
        if target.debug:
            cmd += '--backtrace '
        if test is not None:
            cmd += '--run_test=%s' % test
        target.command(cmd)
